package git.soulbgm.security.handler;

import git.soulbgm.common.pojo.ResultData;
import git.soulbgm.common.pojo.ReturnCode;
import git.soulbgm.pojo.entity.User;
import git.soulbgm.security.pojo.LoginUser;
import git.soulbgm.utils.JsonUtil;
import git.soulbgm.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份验证成功处理类
 *
 * @author SoulBGM
 * @date 2020-08-03
 */
@Slf4j
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser userDetails = (LoginUser) authentication.getPrincipal();
        String ip = RequestUtil.getRemoteIpByServletRequest(request, true);
        log.info("{},登录成功,登录IP: {}", userDetails.getNickname(), ip);
        ResultData resultData = ResultData.getResultData(ReturnCode.LOGIN_SUCCESS, userDetails);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JsonUtil.toJson(resultData));
    }

}
